package com.vite.captcha.util;

import com.vite.captcha.constants.CaptchaTypeConstants;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import lombok.Data;
import lombok.SneakyThrows;

/**
 * 验证码工具类
 */
public class CaptchaUtil {

    private static final int DEFAULT_LENGTH = 4;

    @SneakyThrows
    public static CaptchaInfo getImageToBase64(String type){
        CaptchaInfo captchaInfo = new CaptchaInfo();
        switch (type){
            case CaptchaTypeConstants.PNG:
                SpecCaptcha specCaptcha = new SpecCaptcha();
                specCaptcha.setLen(DEFAULT_LENGTH);
                //字符类型仅在SpecCaptcha和GifCaptcha有效
                //可选TYPE_ONLY_CHAR|TYPE_ONLY_NUMBER|TYPE_NUM_AND_UPPER|TYPE_DEFAULT
                specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
                //字体Captcha.FONT_1-Captcha.FONT_10
                specCaptcha.setFont(Captcha.FONT_10);
                captchaInfo.setVerifyCode(specCaptcha.text().toLowerCase());
                captchaInfo.setImg(specCaptcha.toBase64(""));
                break;
            case CaptchaTypeConstants.GIF:
                Captcha gifCaptcha = new GifCaptcha();
                gifCaptcha.setLen(DEFAULT_LENGTH);
                gifCaptcha.setCharType(Captcha.TYPE_DEFAULT);
                gifCaptcha.setFont(Captcha.FONT_1);
                captchaInfo.setVerifyCode(gifCaptcha.text().toLowerCase());
                captchaInfo.setImg(gifCaptcha.toBase64(""));
                break;
            case CaptchaTypeConstants.CHINESE:
                ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
                chineseCaptcha.setLen(DEFAULT_LENGTH);
                captchaInfo.setVerifyCode(chineseCaptcha.text().toLowerCase());
                captchaInfo.setImg(chineseCaptcha.toBase64(""));
                break;
            case CaptchaTypeConstants.CHINESE_GIF:
                ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha();
                chineseGifCaptcha.setLen(DEFAULT_LENGTH);
                captchaInfo.setVerifyCode(chineseGifCaptcha.text().toLowerCase());
                captchaInfo.setImg(chineseGifCaptcha.toBase64(""));
                break;
            case CaptchaTypeConstants.ARITHMETIC:
                //继承了算数验证码类ArithmeticCaptchaAbstract
                ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha();
                arithmeticCaptcha.setFont(Captcha.FONT_5);
                captchaInfo.setVerifyCode(arithmeticCaptcha.text().toLowerCase());
                captchaInfo.setImg(arithmeticCaptcha.toBase64(""));
                break;
        }
        return captchaInfo;

    }

    /**
     * 验证码实体,img为base64
     */
    @Data
    public static class CaptchaInfo {

        private String img;

        private String verifyCode;

    }

}

